// pages/seal/orderList/orderList.js
const config = require('../../../utils/config.js');

Page({
  data: {
    loading: true,
    error: '',
    orderList: [],
    page: 1,
    hasMore: true,
    status: '', // 订单状态筛选
    statusText: '', // 状态文本
    pagination: {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      totalPages: 0
    }
  },

  onLoad(options) {
    // 接收状态参数
    if (options.status) {
      const status = options.status;
      const statusText = status === '全部' ? '' : status;
      this.setData({
        status: status,
        statusText: statusText
      });
      
      // 动态设置页面标题
      if (status !== '全部') {
        wx.setNavigationBarTitle({
          title: `${status}订单`
        });
      }
    }
    this.loadOrderList();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshOrderList();
  },

  // 加载订单列表
  loadOrderList() {
    // 如果是第一页，显示加载状态
    if (this.data.page === 1) {
      this.setData({
        loading: true,
        error: ''
      });
    }

    wx.request({
      url: `${config.baseUrl}/seal/getOrderList`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || ''
      },
      data: {
        pageNum: this.data.page,
        pageSize: 10,
        status: this.data.status === '全部' ? '' : this.data.status
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newOrders = res.data.data.orderList || [];
          const pagination = res.data.data.pagination || {};
          
          // 处理订单数据，添加有效性标记
          const processedOrders = newOrders.map(order => ({
            ...order,
            // 新增：根据数值状态映射展示用颜色类
            statusClass: this.mapStatusToClass(order.status),
            hasValidReasons: this.hasValidArrayContent(order.reasons),
            hasValidSealClassify: this.hasValidArrayContent(order.sealClassifyArr)
          }));
          
          console.log(`第${this.data.page}页，获取${processedOrders.length}条数据，总页数：${pagination.totalPages}，当前页：${pagination.pageNum}`);
          
          this.setData({
            orderList: this.data.page === 1 ? processedOrders : [...this.data.orderList, ...processedOrders],
            hasMore: pagination.pageNum < pagination.totalPages,
            pagination: pagination,
            loading: false
          });
        } else {
          this.setData({
            error: res.data.msg || '获取订单列表失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取订单列表失败:', err);
        this.setData({
          error: '网络错误，请稍后重试',
          loading: false
        });
      }
    });
  },

  // 刷新订单列表
  refreshOrderList() {
    console.log('刷新订单列表，重置到第一页');
    this.setData({
      page: 1,
      hasMore: true,
      orderList: [], // 清空现有数据
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        totalPages: 0
      }
    });
    this.loadOrderList();
  },

  // 检查数组是否有有效内容
  hasValidArrayContent(arr) {
    if (!arr || !Array.isArray(arr) || arr.length === 0) {
      return false;
    }
    return arr.some(item => item && item !== '' && item.trim() !== '');
  },

  // 将后端数值状态映射为样式类
  mapStatusToClass(statusCode) {
    switch (statusCode) {
      case 0: // 待付款
        return 'status-warning';
      case 1: // 待处理
        return 'status-info';
      case 2: // 处理中
        return 'status-primary';
      case 3: // 提交备案
        return 'status-secondary';
      case 4: // 已发货
        return 'status-success';
      case 5: // 退款/售后
        return 'status-danger';
      case 6: // 已完成
        return 'status-finish';
      default:
        return 'status-secondary';
    }
  },

  // 复制订单号
  handleCopyOrderNo(e) {
    try {
      // 安全地阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
      const orderNo = e.currentTarget.dataset.orderno;
      console.log('复制订单号:', orderNo);
      
      if (!orderNo) {
        wx.showToast({
          title: '订单号为空',
          icon: 'error',
          duration: 1500
        });
        return;
      }
      
      // 先显示加载提示
      wx.showToast({
        title: '正在复制...',
        icon: 'loading',
        duration: 1000
      });
      
      wx.setClipboardData({
        data: orderNo,
        success: () => {
          console.log('复制成功:', orderNo);
          wx.showToast({
            title: '订单号已复制',
            icon: 'success',
            duration: 1500
          });
        },
        fail: (err) => {
          console.error('复制失败:', err);
          wx.showToast({
            title: '复制失败',
            icon: 'error',
            duration: 1500
          });
        }
      });
    } catch (error) {
      console.error('复制订单号失败:', error);
      wx.showToast({
        title: '复制失败',
        icon: 'error',
        duration: 1500
      });
    }
  },



  // 查看订单详情
  handleViewDetail(e) {
    try {
      // 安全地阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
      const order = e.currentTarget.dataset.order;
      if (order && order.id) {
        this.navigateToOrderDetail(order.id);
      }
    } catch (error) {
      console.error('查看订单详情失败:', error);
    }
  },

  // 跳转到订单详情页
  navigateToOrderDetail(orderId) {
    console.log('跳转到订单详情页，orderId:', orderId);
    wx.navigateTo({
      url: `/pages/seal/orderDetail/orderDetail?orderId=${orderId}`
    });
  },

  // 立即付款
  handlePay(e) {
    try {
      // 安全地阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
      const order = e.currentTarget.dataset.order;
      if (order && order.id) {
        // 跳转到订单页面进行支付
        wx.navigateTo({
          url: `/pages/seal/order/order?orderId=${order.id}&price=${order.payPrice}`
        });
      }
    } catch (error) {
      console.error('跳转支付页面失败:', error);
      wx.showToast({
        title: '跳转失败，请重试',
        icon: 'error',
        duration: 2000
      });
    }
  },

  // 查看物流
  handleViewLogistics(e) {
    try {
      // 安全地阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
      const order = e.currentTarget.dataset.order;
      if (order && order.courierNo) {
        // 跳转到物流页面
        wx.navigateTo({
          url: `/pages/seal/logistics/logistics?courierNo=${encodeURIComponent(order.courierNo)}&orderNo=${encodeURIComponent(order.orderNo || '')}`
        });
      } else {
        wx.showToast({
          title: '暂无物流信息',
          icon: 'none',
          duration: 1500
        });
      }
    } catch (error) {
      console.error('查看物流失败:', error);
      wx.showToast({
        title: '查看物流失败',
        icon: 'error',
        duration: 1500
      });
    }
  },

  // 申请退款
  handleRefund(e) {
    try {
      // 安全地阻止事件冒泡
      if (e && typeof e.stopPropagation === 'function') {
        e.stopPropagation();
      }
      const order = e.currentTarget.dataset.order;
      if (order && order.id) {
        wx.showModal({
          title: '申请退款',
          content: '确认申请退款吗？退款将在1-3个工作日内处理。',
          success: (res) => {
            if (res.confirm) {
              this.processRefund(order);
            }
          }
        });
      }
    } catch (error) {
      console.error('申请退款失败:', error);
    }
  },

  // 处理退款
  processRefund(order) {
    wx.showLoading({
      title: '正在申请...'
    });

    wx.request({
      url: `${config.baseUrl}/seal/refundOrder`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || ''
      },
      data: {
        orderId: order.id
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          wx.showToast({
            title: '退款申请已提交',
            icon: 'success',
            duration: 2000
          });
          // 刷新订单列表
          setTimeout(() => {
            this.refreshOrderList();
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.msg || '申请失败',
            icon: 'error',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('退款申请失败:', err);
        wx.showToast({
          title: '申请失败，请重试',
          icon: 'error',
          duration: 2000
        });
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshOrderList();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      console.log('触发上拉加载更多，当前页：', this.data.page);
      this.setData({
        page: this.data.page + 1
      });
      this.loadOrderList();
    } else if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1500
      });
    }
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '我的订单',
      path: '/pages/seal/orderList/orderList'
    };
  }
});